package top.xin1901.j2ecd.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import top.xin1901.j2ecd.beans.User;
import top.xin1901.j2ecd.common.response.R;
import top.xin1901.j2ecd.service.UserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author HeYunjia
 */

@RestController
@CrossOrigin("*")
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping
    public R postUserOne(@RequestBody User user) {
        user = userService.insertOne(user);
        return user == null
                ? R.fail()
                : R.success().add("user", user);
    }

    @DeleteMapping("/{userId}")
    public R deleteUserOne(@PathVariable Long userId) {
        return userService.deleteByPrimaryKey(userId)
                ? R.success()
                : R.fail();
    }

    @PutMapping
    public R updateUserOne(@RequestBody User user) {
        user = userService.updateByPrimaryKey(user);
        return user == null
                ? R.fail()
                : R.success().add("user", user);
    }

    @GetMapping
    public R getUserAll() {
        return R.success()
                .add("users", userService.selectAll());
    }

    @GetMapping("/{pageNumber}/{pageSize}")
    public R getUserPage(@PathVariable Integer pageNumber,
                         @PathVariable Integer pageSize) {

        PageHelper.startPage(pageNumber, pageSize);

        List<User> lists = userService.selectAll();

        return R.success()
                .add("page", new PageInfo<>(lists));
    }

    @GetMapping("/{userId}")
    public R getUserOne(@PathVariable Long userId) {
        return R.success()
                .add("user", userService.selectOne(userId));
    }
}
